package com.funo.ehealth.main;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.funo.ehealth.DB.DbcpConnectionPool;
import com.funo.ehealth.thread.AbstractThread;

/** 
 * 业务模块主线程
 * 
 * @version V1.1
 * @author zhangguangying
 * @date 2012-11-17
 */
public class BussinessProcess {
	
	/**
	 * 业务模块主线程日志记录器
	 */
	public static final Log log = LogFactory.getLog(BussinessProcess.class);
	
	public static void main(String[] args) {
		
		try {
			//初始化myconfig.properties
			BussinessMgr.loadMyConfig();
		} catch (Exception e) {
			log.error("初始化myconfig.properties配置异常，系统准备退出",e);
			System.exit(1);
		}
		
		try {
			//初始化数据库连接
			DbcpConnectionPool.init();
		} catch (Exception e) {
			log.error("初始化数据库连接异常，系统准备退出",e);
			System.exit(1);
		}
		
		//初始化各线程
		if (!initThreads()) {
			log.error("初始化各线程，系统准备退出");
			System.exit(1);
		}
		
		//启动各线程
		ThreadMgr.startThreads();
		
		//主线程等待退出
		waitExit();
		
		//退出各线程
		terminate();
	}
	
	/**
	 * 初始化各线程
	 * @return 
	 */
	private static boolean initThreads() {
		if (ThreadMgr.cpOrderReadThread.init()
				&& ThreadMgr.cpMsgReadThread.init()
				&& ThreadMgr.vgopOrderReadThread.init()
				&& ThreadMgr.vgopUnorderReadThread.init()
				&& ThreadMgr.cpOrderThread.init()
				&& ThreadMgr.cpMsgThread.init()
				&& ThreadMgr.vgopOrderThread.init()
				&& ThreadMgr.vgopUnorderThread.init()) {
			return true;
		}
		return false;
	}
	
	/**
	 *  退出各线程
	 */
	private static void terminate(){
		try {
			Thread[] threads = new Thread[ThreadMgr.threadGroup.activeCount()];
			ThreadMgr.threadGroup.enumerate(threads);
			for (int i = 0; i < threads.length; i++) {
				AbstractThread thread = (AbstractThread) threads[i];
				if(thread == null){
					continue;
				}
				thread.terminateHandler();
			}
		} catch (Exception e) {
			log.error("主线程非正常退出，退出时异常。",e);
			System.exit(0);
		}
		
		log.info("主线程已退出。");
		System.exit(0);
	}
	
	/**
	 * 主线程进入等待状态
	 */
	private static void waitExit() {
		log.info("主线程处于等待中......");
		synchronized (BussinessProcess.class) {
			try {
				BussinessProcess.class.wait();
			} catch (Exception e) {
				log.error("主线程wait时发生异常", e);
			}
		}
	}

	/**
	 * 通知主线程退出
	 */
	public static void notifyExit() {
		log.info("主线程准备退出");
		synchronized (BussinessProcess.class) {
			BussinessProcess.class.notify();
		}
	}
}
